package com.ohuang.launcher;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import java.lang.ref.WeakReference;

public class ActivityManager implements Application.ActivityLifecycleCallbacks {

    private ActivityManager() {
    }

    private static final class InstanceHolder {
        static final ActivityManager instance = new ActivityManager();
    }

    public static ActivityManager getInstance() {
        return InstanceHolder.instance;
    }

    private WeakReference<Activity> resumeActivity;
    private boolean isInit = false;

    public void attach(Application application) {
        if (!isInit) {
            application.registerActivityLifecycleCallbacks(this);
            isInit = true;
        }
    }

    public Activity getResumeActivity(){
        if (resumeActivity!=null){
            return resumeActivity.get();
        }
        return null;
    }


    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        resumeActivity = new WeakReference<>(activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {
        resumeActivity = new WeakReference<>(activity);
    }

    @Override
    public void onActivityResumed(Activity activity) {
        resumeActivity = new WeakReference<>(activity);
    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        if (resumeActivity != null && resumeActivity.get() == activity) {
            resumeActivity = null;
        }
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        if (resumeActivity != null && resumeActivity.get() == activity) {
            resumeActivity = null;
        }
    }

}
